import React, { Component } from 'react';
import { HashRouter as Router, Route, Switch } from 'react-router-dom';
import NoticeCenter from './components/NoticeCenter';
import TrainingNotice from './components/TrainingNotice';
import NoticeDetails from './components/NoticeDetails';
import Logidn from '../common/compont/Logidn';
import ErrorTips from '../common/compont/ErrorTips';
import Error from '../common/compont/Error';
import { Spin, message } from 'antd';
import 'antd/dist/antd.css';
import './components/scss/index.scss';
import { getData, getData1, postData1, getQueryVariable } from "../common/js/fetch";
import '@wangeditor/editor/dist/css/style.css'
import { lgAlert } from 'lancoo-web-ui';
import 'lancoo-web-ui/dist/style.css'
import 'lg-select-modal/dist/index.css';
import { requireSystemTheme, setSystemTheme } from 'lancoo-web-ui';

message.config({
  top: 100,
  duration: 2,
  maxCount: 1,
});


// sessionStorage.setItem('token', '20C7B277-0969-4B54-8B09-6723F4B8DB4A');
class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      start: 0,
      sysId: '222',
      lockerId: '619',
      skin: ''
    };
  }
  alertAInfo2 = () => {
    let alert = lgAlert.show({
      duration: 0,
      content: '您当前的身份没有访问该应用的权限，点击确定返回办公平台',
      tipType: 'info',
      tipSize: 'small',
      tipMouldType: 'A',
      isShowCloseBtn: false,
      showConfirm: false,
      closeText: "知道了",
      onCancel: () => {
        lgAlert.close(alert.index);
        this.openBaseUrl();
      }
    });
  }
  openBaseUrl = () => {
    window.open(sessionStorage.getItem('baseUrl'), '_self');
  }
  componentDidMount() {
    let token = sessionStorage.getItem('token') || getQueryVariable('lg_tk');
    console.log(window.location.href, getQueryVariable('lg_tk'), 'token')
    let isManage = getQueryVariable('isManage');
    console.log(isManage)
    if (isManage === '1') {
      sessionStorage.setItem('isManage', isManage);
    } else {
      sessionStorage.setItem('isManage', '2');
    }
    //用户信息获取
    getData('/api/common/user', { token: token }).then(res => res.json()).then(res => {
      if (res.code == 200 && res.data) {
        // console.log('res.data', res.data);
        let data = res.data;
        let eduData = res.data
        if (data.userType === '0' || data.userType === '6' || data.userType === '7' || data.userType === '8') {
          data.role = '管理员';
        } else {
          data.role = '非管理员';
        }
        sessionStorage.setItem('userInfo', JSON.stringify(data));
        // 2023-09-14 适配高级管理员
        let identityList = data.identityList;
        let identity = identityList.find(item => item.identityCode === getQueryVariable('lg_ic'))
        if(identity?.advanced == 1){
          sessionStorage.setItem('isAdvanced',1);
        }else{
          sessionStorage.setItem('isAdvanced',0);
        }
        //学校及系统信息获取
        getData('/api/common/system/info', {
          // eduId: data.eduId
        })
          .then(res => res.json())
          .then(res => {
            if (res.code == 200 && res.data) {
              let schoolData = res.data;
              // console.log(res, 'res1', schoolData.baseUrl);
              sessionStorage.setItem('baseUrl', schoolData.baseUrl);
              sessionStorage.setItem('schoolSystemInfo', JSON.stringify({
                baseUrl: schoolData.baseUrl,
                isVersion: schoolData.isVersion,
                itemUrl: schoolData.itemUrl,
                newsLockerId: '297',
                newsSysId: schoolData.sysId,
                noticeLockerId: '297',
                noticeSysId: schoolData.sysId,
                productUseRange: schoolData.productUseRange,
                eduId: eduData.eduId,
                eduName: eduData.eduName,
                schoolType: schoolData.productType,
              }));
              //验证是否已登录
              if (schoolData) {
                let script = document.createElement("script");
                script.src = schoolData.baseUrl + "/UserMgr/Login/JS/CheckIsOnline2.js";
                script.type = "text/javascript";
                script.onload = function () {
                  // 重复登录检测 2023-04-11
                  window._LgBase_initCheck(schoolData.baseUrl, token, "270");
                }
                document.getElementsByTagName("head")[0].appendChild(script);
              }
              let url = schoolData.baseUrl + '/UserMgr/PowerMgr/ValidateIdentity'
              console.log(data.userId)

              getData1(sessionStorage.getItem('baseUrl'), 'openapi/v1/system/facade/getSkin', {
                appid: '211',
                token: getQueryVariable('lg_tk'),
              }).then(res => res.json()).then(res => {
                console.log(3333333333333333)
                console.log(res, 11)
                if (res.StatusCode == '200') {
                  // dispatch({
                  //   type: 'SET_SKIN',
                  //   data: `s${res.Data.skin}`
                  // })
                  sessionStorage.setItem('skin', `s${res.Data.skin}`);
                  this.setState({
                    skin: `s${res.Data.skin}`
                  })
                }
              })

              postData1(url, {
                IdentityCode: getQueryVariable('lg_ic'),
                ModuleID: isManage === '1' ? 264002 : 264003,
                UserID: data.userId
              })
                .then(res => { return res.json() })
                .then(res => {
                  console.log(res)
                  if ((res.StatusCode == "200" && res.Data == true) || sessionStorage.getItem('isManage') == '2') {
                    getData('api/common/system/list', {
                      sysIds: 'U10'
                    },
                    ).then((res) => {
                      return res.json();
                    }).then((json) => {
                      console.log(json)
                      sessionStorage.setItem('previewIP', JSON.stringify(json.data));
                    })
                    //锁控校验
                    getData('api/commons/locker/check', {
                      // sysId: schoolData.noticeSysId,
                      // lockerId: schoolData.noticeLockerId,
                      sysId: this.state.sysId,
                      lockerId: this.state.lockerId,
                      productUseRange: schoolData.productUseRange,
                      eduId: schoolData.schoolId,
                    }).then(data => {
                      return data.json()
                    }).then(json => {
                      if (json.code == "200" && json.data.result == '1') {
                        console.log('json.data', json.data);
                        if (Number(json.data.maxPoint) > 0) {
                          sessionStorage.setItem('StandardEdition', 1);
                        } else {
                          sessionStorage.setItem('StandardEdition', 0);
                        }
                        //获取消息中心地址
                        getData('api/common/system/list', {
                          sysIds: '210'
                        }).then(data => {
                          return data.json()
                        }).then(json => {
                          if (json.code == "200" && json.data) {
                            sessionStorage.setItem('PsnMgrLgAssistantAddr', json.data.webSvrAddr);
                            sessionStorage.setItem('PsnMgrToken', token);
                            sessionStorage.setItem('PsnMgrMainServerAddr', schoolData.baseUrl);
                            sessionStorage.setItem('PsnMgrLoading', 1);
                            //获取office-platform地址
                            getData('api/common/system/list', {
                              sysIds: '264'
                            }).then(data => {
                              return data.json()
                            }).then(json => {
                              if (json.code == "200" && json.data) {
                                console.log(json.data)
                                sessionStorage.setItem('officePlatform', JSON.stringify(json.data));
                                this.setState({
                                  start: 1
                                })
                              }
                            });
                          }
                        });
                      }

                    });
                  } else {
                    this.alertAInfo2();
                  }
                })

            }

          })

      } else {
        let url = window.location.href;
        url = url.split('?');
        if (url.length > 1 && url[1].indexOf('&') > -1) {
          let pram = url[1].split('&');
          url = url[0] + '?';
          pram.map((item) => {
            if (item.indexOf('lg_tk=') === -1) {
              url += item + '&';
            }
          })
          url = url.slice(0, -1);
        } else {
          url = url[0];
        }
        if (url.slice(-2) == '#/') {
          url = url.slice(0, -2);
        }
        url = encodeURIComponent(url);
        sessionStorage.removeItem('token');
        window.open(sessionStorage.getItem('baseUrl') + '?lg_sysid=' + '222' + '&lg_preurl=' + url, '_self');
        console.log('请重新登录！');
      }
    })
  }
  render() {
    let basicPlatformAddress = sessionStorage.getItem("baseUrl"); //基础平台地址
    let appId = '264'; //子系统ID
    let token = sessionStorage.getItem("token"); //用户令牌
    console.log(basicPlatformAddress)
    /**
    * @description  : 此处用于非代理下的子系统，如另外需要部署的子系统调用；可以参考一卡通
    * @waring  : 注：此方法有请求，会导致部分系统产生跨域无法正常调用的情况，请子系统对接基础平台后参考调用形式四
    * @waring  : 注：如果控制台打印 “[web-ui] 缓存未获取到用户主题,请自行调用设置主题色工具,如已添加请忽略此打印” 请用此方法；
    */
    window._defaultThemeColor.error(() => {
      // debugger
      requireSystemTheme(basicPlatformAddress, appId, token)
      // debugger
    })
    // requireSystemTheme(basicPlatformAddress, appId, token);
    return (
      <div className="App">
        {this.state.start === 1 ? <div>
          <div>
            {/* <Search></Search> */}
            <Router>
              {/* exact表示绝对匹配 */}
              {/* 在react-router中每一个Route相当于一个组件 */}
              {/* 在传递参数的时候可以设置成 :参数名? 表示可选参数 */}
              {/* Switch表示只匹配一个符合条件的路由 */}
              <Switch>
                <Route path="/" exact component={NoticeCenter} />
                <Route path="/NoticeContent" component={NoticeDetails} />
                <Route path="/trainingNotice" component={TrainingNotice} />
                <Route path="/404" component={Logidn} />
                <Route path="/Error" component={Error} />
                <Route path="/ErrorTips" component={ErrorTips} />
              </Switch>
            </Router>
          </div>
        </div> : ''}
        <div className="example" style={{ display: 'none', height: document.documentElement.clientHeight + 'px', lineHeight: document.documentElement.clientHeight + 'px' }}> <Spin size="large" /></div>
      </div>
    );
  }
}
export default App;